package com.jueling.culture.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.ArrayList;
import java.util.List;

/**
 * @author linp
 * @date 2022/02/18
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "AUTHORITY_INFO")
public class AuthorityInfo {
    /**
     * 权限编码
     */
    @Id
    private String code;

    /**
     * 权限描述
     */
    private String describe;

    /**
     * 父权限
     */
    @Column(name = "p_code")
    private String pCode;

    /**
     * 排序
     */
    private Integer sort;

    /**
     * 备注
     */
    private String remarks;

    /**
     * 子权限集合
     */
    @Transient
    List<AuthorityInfo> children = new ArrayList<AuthorityInfo>();

    public static List<AuthorityInfo> parseTree(List<AuthorityInfo> list){
        List<AuthorityInfo> treeList=new ArrayList<AuthorityInfo>();

        //添加一级权限
        for (AuthorityInfo authorityInfo : list) {
            if("0".equals(authorityInfo.getPCode())){
                treeList.add(authorityInfo);
            }
        }

        //递归添加所有级别的权限
        for (AuthorityInfo parent : treeList) {
            recursiveTree(parent,list);
        }
        return treeList;

    }
    private static void recursiveTree(AuthorityInfo parent, List<AuthorityInfo> list){
        for (AuthorityInfo authorityInfo : list) {
            if(parent.getCode().equals(authorityInfo.getPCode())){
                recursiveTree(authorityInfo,list);
                parent.getChildren().add(authorityInfo);
            }
        }
    }
}